package com.google.gwt.it2tool.client.widget;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.it2tool.client.ClientDataCache;
import com.google.gwt.it2tool.client.ClientDataCache.DataChangeHandler;
import com.google.gwt.it2tool.client.Production;
import com.google.gwt.user.client.ui.Label;

public class ProductLabel extends Label {
	
	private ClientDataCache dataCache;
	
	private ArrayList<IProductClickedHandler> prodClickHandlers = new ArrayList<IProductClickedHandler>();
	
	private final Production production;

	public ProductLabel(Production prod){
		super(prod.getName());
		
		dataCache = ClientDataCache.getInstance();
		
		production=prod;
		
		addStyleName("clickableLabel");
		
		addClickHandler(new ClickHandler() {			
			public void onClick(ClickEvent event) {
				triggerOnProductClicked(production, event);
			}
		});
		
		addAttachHandler(new Handler() {			
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if (event.isAttached()){
					dataCache.addDataChangeHandler(changeHandler);
				}else{
					dataCache.removeDataChangeHandler(changeHandler);
				}
				
			}
		});
		
		setStyleBasedOnRecipe();		
	}	

	public void addIProductClickedHandler(IProductClickedHandler handler){
		prodClickHandlers.add(handler);
	}
	
	public void removeIProductClickedHandler(IProductClickedHandler handler){
		if(handler!=null && prodClickHandlers.contains(handler)){
			prodClickHandlers.remove(handler);
		}
	}
	
	public void triggerOnProductClicked(Production production,ClickEvent event){
		for(IProductClickedHandler h: prodClickHandlers){
			h.onProductClicked(production, event);
		}
	}
	
	public interface IProductClickedHandler{
		public void onProductClicked(Production production, ClickEvent event);
	}
	
	private void setStyleBasedOnRecipe(){
		if(dataCache.getRecipes().keySet().contains(production.getName())){
			removeStyleName("recipeUnAvailableProductLabel");
			addStyleName("recipeAvailableProductLabel");
		}else{
			removeStyleName("recipeAvailableProductLabel");
			addStyleName("recipeUnAvailableProductLabel");
		}
	}
	
	private DataChangeHandler changeHandler = new DataChangeHandler() {
		
		@Override
		public void onRecipeDataChanged() {
			setStyleBasedOnRecipe();			
		}
		
		@Override
		public void onPrototypeDataChanged() {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onMassProductionDataChanged() {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onFactoryDataChanged() {
			// TODO Auto-generated method stub
			
		}
	};
}
